const { contextBridge, ipcRenderer,app,MenuItem, BrowserWindow, ipcMain, nativeTheme, screen } = require('electron')
const path = require('path')
const DataStore = require('../../app-store');
const dataStore = new DataStore();
let mainWindow
let option = screen.getPrimaryDisplay().size
let urlParams = {}

exports.menu = function (menu, tray) {
    menu.append(new MenuItem({
        label: 'OPEN-AI',
        click: function(){
            createMainWindow()
        }
    }))
    tray.setTitle('插件')
}

app.whenReady().then(()=>{
    ipcMain.on('set-zoom-in',(event,...args)=>{
        mainWindow.maximize()
    })
    ipcMain.on('set-zoom-out',(event,...args)=>{
        mainWindow.minimize()
    })
    ipcMain.on('set-close',(event,...args)=>{
        mainWindow.close()
    })
    ipcMain.handle('dark-mode:toggle',()=>{
        console.log(nativeTheme.shouldUseDarkColors)
        if( nativeTheme.shouldUseDarkColors ){
            nativeTheme.themeSource='light'
        }else{
            nativeTheme.themeSource='dark'
        }
        return nativeTheme.shouldUseDarkColors
    })
    ipcMain.handle('dark-mode:system',()=>{
        nativeTheme.themeSource='system'
    })
})

function createMainWindow(){
    const width = parseInt(urlParams.width) || option.width
    const height = parseInt(urlParams.height) || option.height
    if(mainWindow&&!mainWindow.isDestroyed()){
        mainWindow.setSize(width, height)
    } else{
        mainWindow = new BrowserWindow({
            width,
            height,
            titleBarStyle: 'hiddenInset', // 隐藏标题栏
            // resizable: false,
            frame: false,
            minimizable: true,
            maximizable: true,
            closable: true,
            // transparent: true,
            webPreferences: {
                contextIsolation: true,// 语镜隔离
                nodeIntegration:true,// 允许在渲染进程中使用Node.js API
                preload: path.join(__dirname, '/preload/index.js'),
                sandbox: false
            }
        })

        // mainWindow.loadFile(path.join(__dirname, '/renderer/index.html'))
        mainWindow.loadURL(process.env.NODE_ENV === 'development' ? 'http://localhost:8080': `file://${__dirname}/renderer/index.html`)

        // window.loadURL(`file://${__dirname}/renderer/index.html`);
        mainWindow.webContents.openDevTools()
    }
}
